package com.appspot.mscheckers;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class ChatServlet extends HttpServlet{
	  /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");

		if(req.getParameter(Constant.ACTION) == null ){
			return;
		}
		
		if(req.getParameter(Constant.ACTION).toString().equals(Constant.SEND_MESSAGE) ){
			//Gson gson = new Gson();
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
			String userId = req.getParameter(Constant.USER_ID).toString();
			Message msg = gson.fromJson(req.getParameter(Constant.MESSAGE).toString(), Message.class);
			String rId = msg.getrId();
			
			if( userId.equals(msg.getsId()) && Checkers.userMap.get(userId) != null && Checkers.userMap.get(rId) != null ){
				//---------ICI Tester la valider du message-------------
				ChannelService channelService = ChannelServiceFactory.getChannelService();
			    channelService.sendMessage(new ChannelMessage(rId, "{\""+Constant.MESSAGE_TYPE+"\":\""+Constant.MESSAGE+"\"}"));
			    channelService.sendMessage(new ChannelMessage(rId, gson.toJson(msg)));
			}else if(userId.equals(msg.getsId()) ){
				ChannelService channelService = ChannelServiceFactory.getChannelService();
			    channelService.sendMessage(new ChannelMessage(userId, "{\""+Constant.MESSAGE_TYPE+"\":\""+Constant.ERROR+"\"}"));
			    channelService.sendMessage(new ChannelMessage(userId, gson.toJson(new String("Code : "+Constant.ERR_CODEOO1+" Message has not been sent to : "+rId))));				
			}
			
		}
		
	}
	
}
